package com.zhl.study.threadWait;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @description 工作线程的任务
 * @Author: z156940l@outlook.com
 * @className Worker
 * @Date: 2024/5/23 11:09
 */
@Slf4j
public class Worker implements Runnable {
    private CyclicBarrier barrier;

    public Worker(CyclicBarrier barrier) {
        this.barrier = barrier;
    }

    @Override
    public void run() {
        try {
            // 模拟工作线程执行任务
            Thread.sleep(2000);
            log.info("{} is waiting on barrier", Thread.currentThread().getName());

            // 等待其他线程到达barrier
            barrier.await();

            // 所有线程都到达barrier后,继续执行其他操作
            log.info("{} has crossed the barrier", Thread.currentThread().getName());
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}